package utils

import (
	"encoding/json"
	"fmt"
	"gocolly/model"
	"gocolly/spider"
	"os"
	"time"
)

type ResponseDivideSection struct {
	Code    any               `json:"code"`
	Message any               `json:"message"`
	Data    DivideSectionItem `json:"data"`
}

type DivideSectionItem struct {
	Search map[string]model.DivideSection `json:"search"`
}

// gaokao.cn 一分一段省份直辖市代号
var Provinces = map[string]string{
	"11": "北京",
	"12": "天津",
	"13": "河北",
	"14": "山西",
	"15": "内蒙古",
	"21": "辽宁",
	"22": "吉林",
	"23": "黑龙江",
	"31": "上海",
	"32": "江苏",
	"33": "浙江",
	"34": "安徽",
	"35": "福建",
	"36": "江西",
	"37": "山东",
	"41": "河南",
	"42": "湖北",
	"43": "湖南",
	"44": "广东",
	"45": "广西",
	"46": "海南",
	"50": "重庆",
	"51": "四川",
	"52": "贵州",
	"53": "云南",
	"61": "陕西",
	"62": "甘肃",
	"63": "青海",
	"64": "宁夏",
}

var Years = []string{
	"2024",
	"2023",
	"2022",
	"2021",
	"2020",
	"2019",
	"2018",
	"2017",
	"2016",
}
var ExamTypes = map[string]string{
	"物理": "2073",
	"历史": "2074",
	"综合": "3",
}
var Batches = map[string]string{
	"本科": "1",
	"专科": "2",
}

// batch:
func GetListSections(year, province, exam_type, batch string) []byte {

	url := `https://static-data.gaokao.cn/www/2.0/section2021/` + year + `/` + province + `/` + exam_type + `/` + batch + `/lists.json`

	headers := map[string]string{
		"Accept": "application/json, text/plain, */*",
		//"Accept-Encoding":    "gzip, deflate, br, zstd",
		"Accept-Language":    "zh-CN,zh;q=0.9",
		"Content-Length":     "202",
		"Content-Type":       "application/json",
		"Origin":             "https://www.gaokao.cn",
		"Priority":           "u=1, i",
		"Referer":            "https://www.gaokao.cn/",
		"Sec-Ch-Ua":          `"Not)A;Brand";v="99", "Google Chrome";v="127", "Chromium";v="127"`,
		"Sec-Ch-Ua-Mobile":   `?0`,
		"Sec-Ch-Ua-Platform": "Windows",
		"Sec-Fetch-Dest":     "empty",
		"Sec-Fetch-Mode":     "cors",
		"Sec-Fetch-Site":     "cross-site",
		"User-Agent":         "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36",
	}

	req := &Request{
		URL:     url,
		Method:  "GET",
		Timeout: 10 * time.Second,
		Headers: headers,
	}

	res := req.Do()
	return res
}

func DecodeDivideSectionJsonStrAndSave(jsonStr []byte, province, year, examType, batch string) (res ResponseDivideSection) {
	err := json.Unmarshal(jsonStr, &res)
	if err != nil {
		os.WriteFile("解析失败.json", []byte(err.Error()+":"+province+"|"+year+"|"+examType+"|"+batch), os.ModePerm)
		return res
	} else {
		for _, section := range res.Data.Search {
			section.Province = province
			section.Year = year
			section.ExamType = examType
			section.BatchName = batch
			model.UpdateOrCreateDivideSection(section)
		}
	}

	return
}

func ExampleDivideSave() {
	fileStr, err := os.ReadFile("./static/province_section.json")
	if err != nil {
		panic("去读文件失败:" + err.Error())
	}
	res := spider.UnmarshalDivideSectionJsonStr(fileStr)
	for provinceCode, proviceDatas := range res.Data.Data {
		for year, yearData := range proviceDatas {
			hasInserted := false
			//一，判断是综合，理科，文科
			if yearData.Zero.NameToStr() != "" {
				ExamType := yearData.Zero.NameToStr()
				if yearData.Level.Zero.NameToStr() != "" {
					first := model.MissOutDivideSection(year, Provinces[provinceCode], ExamType, yearData.Level.Zero.NameToStr())
					if first.ID == 0 {
						fmt.Printf(">>>>省份代码：%s 年份：%s 文理综：%s  批次: %s \n", Provinces[provinceCode], year, ExamType, yearData.Level.Zero.NameToStr())
						jsonStr := GetListSections(year, provinceCode, yearData.Zero.IDToStr(), yearData.Level.Zero.IDToStr()) //年份+省份+文理综+批次
						DecodeDivideSectionJsonStrAndSave(jsonStr, Provinces[provinceCode], year, ExamType, yearData.Level.Zero.NameToStr())
						hasInserted = true
					}
				}
				if yearData.Level.One.NameToStr() != "" {
					first := model.MissOutDivideSection(year, Provinces[provinceCode], ExamType, yearData.Level.One.NameToStr())
					if first.ID == 0 {
						fmt.Printf(">>>>省份代码：%s 年份：%s 文理综：%s  批次: %s \n", Provinces[provinceCode], year, ExamType, yearData.Level.One.NameToStr())
						jsonStr := GetListSections(year, provinceCode, yearData.Zero.IDToStr(), yearData.Level.One.IDToStr()) //年份+省份+文理综+批次
						DecodeDivideSectionJsonStrAndSave(jsonStr, Provinces[provinceCode], year, ExamType, yearData.Level.One.NameToStr())
						hasInserted = true
					}

				}

			}

			if yearData.One.NameToStr() != "" {
				ExamType := yearData.One.NameToStr()
				if yearData.Level.Zero.NameToStr() != "" {
					first := model.MissOutDivideSection(year, Provinces[provinceCode], ExamType, yearData.Level.Zero.NameToStr())
					if first.ID == 0 {
						fmt.Printf(">>>>省份代码：%s 年份：%s 文理综：%s  批次: %s \n", Provinces[provinceCode], year, ExamType, yearData.Level.Zero.NameToStr())
						jsonStr := GetListSections(year, provinceCode, yearData.One.IDToStr(), yearData.Level.Zero.IDToStr()) //年份+省份+文理综+批次
						DecodeDivideSectionJsonStrAndSave(jsonStr, Provinces[provinceCode], year, ExamType, yearData.Level.Zero.NameToStr())
						hasInserted = true

					}

				}
				if yearData.Level.One.NameToStr() != "" {
					first := model.MissOutDivideSection(year, Provinces[provinceCode], ExamType, yearData.Level.One.NameToStr())
					if first.ID == 0 {
						fmt.Printf(">>>>省份代码：%s 年份：%s 文理综：%s  批次: %s \n", Provinces[provinceCode], year, ExamType, yearData.Level.One.NameToStr())
						jsonStr := GetListSections(year, provinceCode, yearData.One.IDToStr(), yearData.Level.One.IDToStr()) //年份+省份+文理综+批次
						DecodeDivideSectionJsonStrAndSave(jsonStr, Provinces[provinceCode], year, ExamType, yearData.Level.One.NameToStr())
						hasInserted = true

					}

				}

			}
			if hasInserted == true {
				time.Sleep(10 * time.Second)
			} else {
				fmt.Print(".")
			}

		}
	}
	fmt.Println("结束")
}
